# coding=utf-8
from django.db import models
from django.db.models import signals
from django.dispatch import receiver

# Create your models here.

class Human(models.Model):
    SEX = (
        ('female', u'女'),
        ('male', u'男'),
    )
    name = models.CharField(max_length=30)
    age = models.IntegerField(default=0)
    has_married = models.BooleanField(default=False)
    sex = models.CharField(max_length=20, default='male', choices=SEX)

    class Meta:
        abstract = True

class Man(Human):
    pass

class Woman(Human):
    pass

class Children(Human):
    father = models.ForeighKey('Man')
    mather = models.ForeighKey('Woman')

class Family(models.Model):
    husband = models.ForeighKey('Man')
    wife = models.ForeighKey('Woman')

    def has_child(self):
        pass


@receiver(signals.pre_save)
def my_pre_save(sender, "instance", "raw", "using", "update_fields", **kwargs):
    if isinstance(instance, BaseModel):
        SyncLog.add_log(instance, 'delete')
    elif isinstance(instance, CountryToSchoolBaseModel):
        #仅县级服务器
        if Setting.getvalue('server_type') == 'country':
            CountryToSchoolSyncLog.add_log(instance, 'delete')
    else:
        return

@receiver(signals.post_save)
def my_post_save(sender, instance, using, **kwargs):
    if isinstance(instance, BaseModel):
        SyncLog.add_log(instance, 'delete')
    elif isinstance(instance, CountryToSchoolBaseModel):
        #仅县级服务器
        if Setting.getvalue('server_type') == 'country':
            CountryToSchoolSyncLog.add_log(instance, 'delete')
    else:
        return


@receiver(signals.pre_delete)
def my_pre_delete(sender, instance, using, **kwargs):
    if isinstance(instance, BaseModel):
        SyncLog.add_log(instance, 'delete')
    elif isinstance(instance, CountryToSchoolBaseModel):
        #仅县级服务器
        if Setting.getvalue('server_type') == 'country':
            CountryToSchoolSyncLog.add_log(instance, 'delete')
    else:
        return

    modelName = sender.__name__

    if modelName == 'Node':
        try:
            key = 'sync_%s' % instance.uuid
            Setting.objects.get(name=key).delete()
        except Exception:
            pass


@receiver(signals.post_delete)
def my_post_delete(sender, instance, using, **kwargs):
    modelName = sender.__name__
    if modelName == 'LessonTeacher':
        # 重新计算TotalTeachers
        try:
            LessonTeacher.calculate_total_teachers(instance)
        except:
            pass
    if constants.BANBANTONG_USE_MONGODB:
        if modelName == 'Class':
            conn = mongo._get_conn()
            conn.banbantong.classes.remove(mongo.class_to_dict(instance))
            conn.close()